<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class BanBeService {

    public static function isFriend($friendId) {
        return BanBe::model()->findByAttributes(array('NguoiDungId1' => Yii::app()->user->id, 'NguoiDungId2' => $friendId)) != null;
    }

    public static function addFriend($friendId) {
        $fr = new BanBe();
        $fr->NguoiDungId1 = Yii::app()->user->id;
        $fr->NguoiDungId2 = $friendId;

        $folRes = TRUE;
        if (!NguoiDungService::isFollowed($friendId)) {
            $td = new TheoDoiNguoiDung();
            $td->NguoiDungId1 = Yii::app()->user->id;
            $td->NguoiDungId2 = $friendId;
            $folRes = $td->save();
        }
        return $fr->save() && $folRes;
    }

    public static function SendFriendRequest($to) {
        return (BanBeService::addFriend($to) && NotificationService::PushFriendRequest($to));
    }

    public static function UnFriend($friendId) {
        $rec = BanBe::model()->findByPk(array('NguoiDungId1' => Yii::app()->user->id, 'NguoiDungId2' => $friendId));

        $Res = TRUE;
        if (NguoiDungService::isFollowed($friendId)) {
            $rec2 = TheoDoiNguoiDung::model()->findByPk(array('NguoiDungId1' => Yii::app()->user->id, 'NguoiDungId2' => $friendId));
            $Res = $rec2->delete();
        }

        return $rec->delete() && $Res;
    }

}
